<?php

namespace App\Kuafu\Order\Jobs;

use App\Kuafu\Common\Jobs\SensorsDataJob;
use App\Kuafu\Common\Service\CommonService;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderCouponSplitModel;
use App\Kuafu\Order\Model\OrderDetailSplitModel;
use App\Kuafu\Order\Model\OrderExternalSplitModel;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Shop\Service\ShopService;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;


/**
 * @description 订单支付消息队列
 *
 * @queueName {PAY_ORDER_QUEUE}
 */
class PayOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * 异常标题
     */
    const EXCEPTION_TITLE = '【 消费队列 】【 订单支付 】';

    /**
     * 队列名称
     *
     * @var string
     */
    public static string $QUEUE_NAME = '{RMS-PAY-ORDER-QUEUE}';

    /**
     * 门店id
     *
     * @var int
     */
    public int $shopId;


    /**
     * 订单id
     *
     * @var int
     */
    public int $orderId;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($shopId, $orderId)
    {
        $this->orderId = $orderId;
        $this->shopId  = $shopId;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            Log::channel('sensors')->info(
                self::EXCEPTION_TITLE,
                Collect(get_object_vars($this))->only(['shopId', 'orderId', 'queue'])->toArray()
            );

            list($orderObject, $orderDetailObject, $orderCouponObject, $orderExternalObject) = $this->getParams();

            // 新增常去门店处理
            ShopService::shopUserUsuallyAdd($orderObject->userId, $this->shopId);

            //丢入神策埋点
//            $this->sensorsDataHandle($orderObject, $orderDetailObject, $orderCouponObject, $orderExternalObject);

        } catch (Exception $e) {
            CommonService::fsLogException(self::EXCEPTION_TITLE, $e,
                Collect(get_object_vars($this))->only(['shopId', 'orderId', 'queue'])->toArray(), true);
        }

    }

    /**
     * @return array
     * @throws Exception
     */
    public function getParams(): array
    {
        //订单信息
        $orderObject = OrderSplitModel::suffix($this->shopId)
                                      ->query()
                                      ->where('orderId', $this->orderId)
                                      ->first();
        if (empty($orderObject)) {
            throw new Exception('订单查询失败');
        }

        //获取菜品详情数据
        $orderDetailObject = OrderDetailSplitModel::suffix($this->shopId)
                                                  ->query()
                                                  ->where('orderId', $this->orderId)
                                                  ->get();

        //获取其他订单数据
        $orderExternalObject = OrderExternalSplitModel::suffix($this->shopId)
                                                      ->query()
                                                      ->where('orderId', $this->orderId)
                                                      ->get();

        //获取订单优惠券使用
        $orderCouponObject = OrderCouponSplitModel::suffix($this->shopId)
                                                  ->query()
                                                  ->where('orderId', $this->orderId)
                                                  ->get();

        return [$orderObject, $orderDetailObject, $orderCouponObject, $orderExternalObject];
    }


    /**
     * 神策埋点处理
     *
     * @param Model|object|static|null $orderObject
     * @param Collection|static[] $orderDetailObject
     * @param Collection|static[] $orderCouponObject
     * @param Collection|static[] $orderExternalObject
     */
    public function sensorsDataHandle($orderObject, $orderDetailObject, $orderCouponObject, $orderExternalObject)
    {
      /*  $oderDetail = [
            'order_time'         => date('Y-m-d H:i:s', $orderObject->createdAt->timestamp),
            //订单时间 |DATETIME|
            'order_no'           => (string)$orderObject->orderId,
            //订单编号 |STRING|
            'order_amount'       => bcdiv($orderObject->originalPrice, 100, 2),
            //订单金额 |NUMBER| 菜品总金额：统计所有菜品⾦额=
            'discount_amount'    => (string)bcdiv($orderObject->discountPrice, 100, 2),
            //优惠折扣 |STRING|
            'pay_amount'         => bcdiv($orderObject->orderShouldPrice - (int)$orderExternalObject->sum('payPrice'),
                100, 2),
            //优惠后金额 |NUMBER| 优惠后的菜品总金额
            'if_consumCoupon'    => (bool)$orderCouponObject->isNotEmpty(),
            //是否使用优惠券 |BOOL|
            'if_chooseBuyCoupon' => !empty($orderExternalObject) && $orderExternalObject->where('type',
                    CodeEnum::ORDER_EXTERNAL_TYPE_COUPON_PACKAGE)->count() > 0,
            'coupon_quantity'    => $orderCouponObject->count(),
            //优惠券数量 |number|
            'comment'            => (string)$orderObject->remark,
            //备注 |STRING| 口味，偏好备注内容
        ];


        Log::channel('sensors')->info(
            self::EXCEPTION_TITLE. '【 订单信息 】',
            $oderDetail
        );

        //丢入神策埋点【 支付订单 】
        SensorsDataJob::dispatch(
            $this->shopId,
            $orderObject->userId,
            SensorsDataJob::TYPE_PAY_ORDER,
            $oderDetail
        )->onQueue(SensorsDataJob::$QUEUE_NAME);


        //丢入神策埋点【 支付订单 】【 菜品详情 】
        $orderDetailObject->each(function ($item) use ($orderObject) {
            $menuDetail = [
                'order_time'         => date('Y-m-d H:i:s', $orderObject->createdAt->timestamp),
                //订单时间 |DATETIME|
                'order_no'           => (string)$item->orderId,
                //订单编号 |STRING|
                'menu_type'          => (string)\App\Kuafu\Product\Enum\CodeEnum::TYPE_PRODUCT_TYPE_TEXT[$item->type] ?? '单品',
                //菜品分类 |STRING| 必吃，素串系列，卤油炸串，套餐类等
                'menu_name'          => (string)$item->productName,
                //菜品名称 |STRING| 如果是套餐组合，传套餐名称
                'menu_originalPrice' => (string)bcdiv($item->originalUnitPrice, 100, 2),
                //菜品原价 |STRING|
                'menu_quantity'      => (string)$item->num,
                //菜品数量 |STRING|
                'menu_amount'        => bcdiv($item->originalPrice, 100, 2),
                //菜品金额 |NUMBER| 菜品⾦额默认为菜品原价*菜品份额
                'discount_amount'    => (string)bcdiv($item->totalDiscountPrice, 100, 2),
                //优惠折扣 |STRING|
                'pay_amount'         => bcdiv($item->payPrice, 100, 2),
                //优惠后金额 |NUMBER| 优惠后的菜品总金额
                'comment'            => (string)$orderObject->remark,
                //备注 |STRING| 口味，偏好备注内容
            ];

            Log::channel('sensors')->info(
                self::EXCEPTION_TITLE. '【 菜品信息 】',
                $menuDetail
            );

            SensorsDataJob::dispatch(
                $this->shopId,
                $orderObject->userId,
                SensorsDataJob::TYPE_PAY_ORDER_MENU_DETAIL,
                $menuDetail
            )->onQueue(SensorsDataJob::$QUEUE_NAME);
        });*/
    }
}
